#include "config_manager.h"
#include "logger.h"
#include <fstream>
#include <sstream>
#include <algorithm>

namespace yquote {

ConfigManager::ConfigManager() = default;

bool ConfigManager::loadConfig(const std::string& config_file) {
    config_file_path_ = config_file;
    
    std::ifstream file(config_file);
    if (!file.is_open()) {
        LOG_ERROR_FMT("无法打开配置文件: %s", config_file.c_str());
        return false;
    }
    
    config_.clear();
    
    std::string line;
    std::string current_section;
    int line_number = 0;
    
    while (std::getline(file, line)) {
        line_number++;
        line = trim(line);
        
        // 跳过空行和注释
        if (line.empty() || line[0] == '#' || line[0] == ';') {
            continue;
        }
        
        // 处理节（section）
        if (line[0] == '[' && line.back() == ']') {
            current_section = line.substr(1, line.length() - 2);
            current_section = trim(current_section);
            continue;
        }
        
        // 处理键值对
        size_t pos = line.find('=');
        if (pos != std::string::npos) {
            std::string key = trim(line.substr(0, pos));
            std::string value = trim(line.substr(pos + 1));
            
            if (!current_section.empty() && !key.empty()) {
                config_[current_section][key] = value;
            }
        } else {
            LOG_ERROR_FMT("配置文件格式错误，行 %d: %s", line_number, line.c_str());
        }
    }
    
    file.close();
    LOG_INFO_FMT("配置文件加载成功: %s", config_file.c_str());
    return true;
}

std::string ConfigManager::getString(const std::string& section, const std::string& key, const std::string& default_value) const {
    auto section_it = config_.find(section);
    if (section_it != config_.end()) {
        auto key_it = section_it->second.find(key);
        if (key_it != section_it->second.end()) {
            return key_it->second;
        }
    }
    return default_value;
}

int ConfigManager::getInt(const std::string& section, const std::string& key, int default_value) const {
    std::string value = getString(section, key);
    if (!value.empty()) {
        try {
            return std::stoi(value);
        } catch (const std::exception&) {
            LOG_ERROR_FMT("配置值转换为整数失败: [%s].%s = %s", section.c_str(), key.c_str(), value.c_str());
        }
    }
    return default_value;
}

double ConfigManager::getDouble(const std::string& section, const std::string& key, double default_value) const {
    std::string value = getString(section, key);
    if (!value.empty()) {
        try {
            return std::stod(value);
        } catch (const std::exception&) {
            LOG_ERROR_FMT("配置值转换为浮点数失败: [%s].%s = %s", section.c_str(), key.c_str(), value.c_str());
        }
    }
    return default_value;
}

bool ConfigManager::getBool(const std::string& section, const std::string& key, bool default_value) const {
    std::string value = getString(section, key);
    if (!value.empty()) {
        std::transform(value.begin(), value.end(), value.begin(), ::tolower);
        return value == "true" || value == "yes" || value == "1" || value == "on";
    }
    return default_value;
}

std::vector<std::string> ConfigManager::getStringList(const std::string& section, const std::string& key, const std::vector<std::string>& default_value) const {
    std::string value = getString(section, key);
    if (!value.empty()) {
        return split(value, ',');
    }
    return default_value;
}

void ConfigManager::setString(const std::string& section, const std::string& key, const std::string& value) {
    config_[section][key] = value;
}

void ConfigManager::setInt(const std::string& section, const std::string& key, int value) {
    config_[section][key] = std::to_string(value);
}

void ConfigManager::setDouble(const std::string& section, const std::string& key, double value) {
    config_[section][key] = std::to_string(value);
}

void ConfigManager::setBool(const std::string& section, const std::string& key, bool value) {
    config_[section][key] = value ? "true" : "false";
}

bool ConfigManager::saveConfig(const std::string& config_file) const {
    std::string file_path = config_file.empty() ? config_file_path_ : config_file;
    
    std::ofstream file(file_path);
    if (!file.is_open()) {
        LOG_ERROR_FMT("无法写入配置文件: %s", file_path.c_str());
        return false;
    }
    
    file << "# YQuote 服务器配置文件\n" << std::endl;
    
    for (const auto& section_pair : config_) {
        file << "[" << section_pair.first << "]" << std::endl;
        for (const auto& key_pair : section_pair.second) {
            file << key_pair.first << " = " << key_pair.second << std::endl;
        }
        file << std::endl;
    }
    
    file.close();
    LOG_INFO_FMT("配置文件保存成功: %s", file_path.c_str());
    return true;
}

void ConfigManager::printConfig() const {
    LOG_INFO("=== 当前配置 ===");
    for (const auto& section_pair : config_) {
        LOG_INFO_FMT("[%s]", section_pair.first.c_str());
        for (const auto& key_pair : section_pair.second) {
            LOG_INFO_FMT("  %s = %s", key_pair.first.c_str(), key_pair.second.c_str());
        }
    }
}

std::string ConfigManager::trim(const std::string& str) const {
    size_t start = str.find_first_not_of(" \t\r\n");
    if (start == std::string::npos) {
        return "";
    }
    size_t end = str.find_last_not_of(" \t\r\n");
    return str.substr(start, end - start + 1);
}

std::vector<std::string> ConfigManager::split(const std::string& str, char delimiter) const {
    std::vector<std::string> result;
    std::stringstream ss(str);
    std::string item;
    
    while (std::getline(ss, item, delimiter)) {
        item = trim(item);
        if (!item.empty()) {
            result.push_back(item);
        }
    }
    
    return result;
}

} // namespace yquote 